<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>

<body>
    <button>发送请求</button>
    <button>取消请求</button>

    <script>
        //获取按钮
        let btns = document.querySelectorAll('button');
        //1. 声明变量
        let cancel = null;

        btns[0].onclick = async function () {
            let res = await axios.get('http://127.0.0.1:8080/server', {
                // 2. 配置 cancelToken 属性
                cancelToken: new axios.CancelToken((c) => {
                    cancel = c;
                })
            });
            console.log(res);
        }

        btns[1].onclick = function(){
            //3. 调用 cancel 函数
            cancel();
        }
    </script>
</body>

</html>